package com.itheima.stock.face.Impl;

import com.google.common.base.Strings;
import com.itheima.stock.face.UserCacheFace;
import com.itheima.stock.mapper.SysPermissionMapper;
import com.itheima.stock.mapper.SysRoleMapper;
import com.itheima.stock.pojo.entity.SysPermission;
import com.itheima.stock.pojo.entity.SysRole;
import com.itheima.stock.service.impl.PermissionServiceImpl;
import com.itheima.stock.service.impl.RoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component("userCacheFace")
public class UserCacheFaceImpl implements UserCacheFace {

    @Autowired
    private PermissionServiceImpl permissionService;

    @Autowired
    private RoleServiceImpl roleService;

    @Cacheable(cacheNames = "userRole", key="#useId")
    @Override
    public List<String> getUserSpringSecurity(Long useId) {
        //获取权限集合
        List<SysPermission> permissionList=this.permissionService.getPermissionByUserId(useId);
        List<String> permsNameList = permissionList.stream().filter(item -> !Strings.isNullOrEmpty(item.getPerms())).map(item -> item.getPerms())
                .collect(Collectors.toList());

        //获取角色集合 基于角色鉴权注解需要将角色前追加ROLE_
        List<SysRole> roleList= roleService.getRoleByUserId(useId);
        List<String> roleNameList = roleList.stream().filter(item -> !Strings.isNullOrEmpty(item.getName()))
                .map(item ->  "ROLE_" + item.getName()).collect(Collectors.toList());

        List<String> auths= new ArrayList<String>();
        auths.addAll(permsNameList);
        auths.addAll(roleNameList);
        return auths;
    }
}
